package com.xone.xapp;

import java.util.LinkedList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;

import com.xone.xapp.HttpUtils.onGetSuccessListener;

public class AutoLoginDataTask extends AsyncTask<String, Integer, String> {

	protected String username = null;
	protected String password = null;
	protected Context context;
	protected AutoLoginDataTask(Context context) {
		this.context = context;
	}
	
	@Override
	protected String doInBackground(String... params) {
		if (isCancelled() || null == params || params.length < 3) {
			return null;
		}
		List<NameValuePair> param = new LinkedList<NameValuePair>();
		param.add(new BasicNameValuePair("person.username", params[0]));
		param.add(new BasicNameValuePair("person.password", params[1]));
		param.add(new BasicNameValuePair("identifyCode", params[2]));
		username = params[0];
		password = params[1];
		return HttpUtils.httpGet(Constants.APP_URL + "/login/loginjson.html", param, new onGetSuccessListener<String>() {
			@Override
			public String onSuccess(int status, String result) {
				return result;
			}
		});
	}
	
	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		JSONObject jsonObject = JSONUtils.getJSONObjectFromString(result);
		Boolean login = JSONUtils.getBooleanFromJSONObject(jsonObject, "login");
		if (!login) {
			JSONObject mapValue = JSONUtils.getJSONObjectForKey(jsonObject, "mapValue");
			String msg = JSONUtils.getStringFromJSONObject(mapValue, "msg");
			if (null != msg) {
				loginFailed(msg);
			}
		} else {
			loginOk(JSONUtils.getJSONObjectForKey(jsonObject, "userMap"));
			ShareUtils.setPrefs(ShareUtils.USERNAME, username, context);
			ShareUtils.setPrefs(ShareUtils.PASSWROR, password, context);
			UserInfo.initUserMap(result);
			UserInfo.login = true;
		}
	}
	
	public void loginOk(JSONObject userMap) {
	}
	
	public void loginFailed(String msg) {
	}

}
